<template>
  <!-- 模块1 -->
  <div class="modular">
    <div class="modular_top">
      <div class="triangle"></div>
      <div class="modular_icon">
        <img src="@/assets/img/zjtszjc.png" alt="">
      </div>
      <h2>近三十天异常报警占比<span v-if="$store.state.building">东湖花园小区{{ $store.state.listData.infoS[0].buildNo < 10 ?
          (Array(2).join(0) + $store.state.listData.infoS[0].buildNo).slice(-2) :
          $store.state.listData.infoS[0].buildNo
      }}栋</span>
      </h2>
    </div>
    <div class="maintain_cont">
      <div class="item">
        <ul>
          <!-- <li><span class="circular color1"></span><span>巡检</span><span class="color1">{{ data.mtIns }}</span>次</li>
          <li><span class="circular color2"></span><span>维修</span><span class="color2">{{ data.mtRepair }}</span>次</li>
          <li><span class="circular color3"></span><span>保养</span><span class="color3">{{ data.mtWell }}</span>次</li>
          <li><span class="circular color4"></span><span>水箱清洗</span><span class="color4">{{ data.mtClear }}</span>次</li> -->
          <li><span class="circular color1"></span><span>水量异常</span></li>
          <li><span class="circular color2"></span><span>TDS异常</span></li>
          <li><span class="circular color3"></span><span>水压异常</span></li>
          <!-- <li><span class="circular color4"></span><span>水质异常</span></li> -->
        </ul>
      </div>
      <div class="loss_cont">
        <div class="loss_cont_left">
          <div class="loos_item">
            <h2><span>累计异常报警次数</span></h2>
            <h3><span>{{ arr.allAlarm }}</span>
              <h4>( 次 )</h4>
            </h3>
          </div>
          <div class="loos_item">
            <h2><span>累计服务次数</span></h2>
            <h3><span>{{ arr.server }}</span>
              <h4>( 次 )</h4>
            </h3>
          </div>
        </div>
        <div class="loss_cont_right">
          <div class="chart-container">
            <div class="chart" ref="chart2"></div>
            <!-- <div class="bg"></div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from '@/assets/utils/api.js'
const color = ['#db7046', '#eed55f', '#39e0be', '#53bbf0']
import { getPie3D, getParametricEquation } from '@/assets/js/chart2.js' //工具类js，页面路径自己修改
// const color = ['#28d4b2', '#cd5a2d', '#37aeea', '#ebd675']

export default {
  name: 'chart',
  data() {
    return {
      tenantid: 1128,
      community: 1,
      buildNo: '',
      arr: [],
      optionData: [
        {
          name: '水量异常',
          value: 1
        },
        {
          name: 'TDS异常',
          value: 1
        },
        {
          name: '水压异常',
          value: 1
        },
        // {
        //   name: '水质异常',
        //   value: 9
        // }
      ],
      statusChart: null,
      option: {}
    }
  },
  created() {
  },
  mounted() {
    setTimeout(() => {
      this.getData()
    }, 2000)
    //根据窗口变化自动调节图表大小
    // const that = this
  },
  methods: {
    // changeData(value) {
    //   this.getData(Number(value))
    // },
    changeBuildNo(id) {
      // console.log(id)
      this.buildNo = id
      this.getData()
      // console.log(5)
    },
    async getData() {
      const res = await api.monthAlramPer({ tenantid: this.tenantid, community: this.community, buildNo: this.buildNo })
      this.arr = res.data
      if(this.arr){
        this.optionData[0].value = this.arr['流量异常'] ? this.arr['流量异常'] : ''
        this.optionData[1].value = this.arr['TDS异常'] ? this.arr['TDS异常'] : ''
        this.optionData[2].value = this.arr['压力异常'] ? this.arr['压力异常'] : ''
      }
      // let arrCnt = []
      // this.optionData.forEach(item => arrCnt.push(item.value))
      // const maxNum = Math.max.apply(null, arrCnt)
      this.setLabel()
      this.initChart()
      window.onresize = () => {
        this.statusChart.resize()
      }
    },
    // 初始化label样式
    setLabel() {
      this.optionData.forEach((item, index) => {
        item.itemStyle = {
          color: color[index]
        }
        item.label = {
          normal: {
            show: true,
            color: color[index],
            textShadowColor: 'rgba(0, 0, 0, 1)',
            textShadowBlur: 5,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1,
            formatter: [
              '{c|{c}}{a|次}',
              '{b|{b}}'
            ].join('\n'), // 用\n来换行
            rich: {
              a: {
                fontSize: 10,
                color: '#fff',
                lineHeight: 10,
                align: 'left'
              },
              b: {
                fontSize: 10,
                color: color[index],
                lineHeight: 10,
                align: 'left'
              },
              c: {
                fontSize: 20,
                color: color[index]
              }
            }
          }
        }
        item.labelLine = {
          normal: {
            lineStyle: {
              width: 1,
              color: 'rgba(255,255,255,0.9)'
            }
          }
        }
      })
    },
    // 图表初始化
    initChart() {
      this.statusChart = this.$echarts.init(this.$refs.chart2)
      // 传入数据生成 option, 构建3d饼状图, 参数工具文件已经备注的很详细
      this.option = getPie3D(this.optionData, 0, 240, 28, 40, 1)
      // this.statusChart.setOption(this.option)

      this.option.series.push({
        name: 'pie2d',
        type: 'pie',
        labelLine: {
          length: window.innerWidth / 150,
          length2: window.innerWidth / 50
        },
        startAngle: -45, //起始角度，支持范围[0, 360]。
        clockwise: false,//饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
        radius: ['50%', '50%'],
        center: ['50%', '50%'],
        data: this.optionData,
        hoverAnimation: false
      })

      this.statusChart.setOption(this.option)
      this.bindListen(this.statusChart)
    },
    // 监听鼠标事件，实现饼图选中效果（单选），近似实现高亮（放大）效果。
    // optionName是防止有多个图表进行定向option传递，单个图表可以不传，默认是opiton
    bindListen(myChart, optionName = 'option') {
      let hoveredIndex = ''
      // 监听 mouseover，近似实现高亮（放大）效果
      myChart.on('mouseover', (params) => {
        // 准备重新渲染扇形所需的参数
        let isSelected
        let isHovered
        let startRatio
        let endRatio
        let k
        // 如果触发 mouseover 的扇形当前已高亮，则不做操作
        if (hoveredIndex === params.seriesIndex) {
          // 否则进行高亮及必要的取消高亮操作
        } else {
          // 如果当前有高亮的扇形，取消其高亮状态（对 option 更新）
          if (hoveredIndex !== '') {
            // 从 option.series 中读取重新渲染扇形所需的参数，将是否高亮设置为 false。
            isSelected = this[optionName].series[hoveredIndex].pieStatus.selected
            isHovered = false
            startRatio = this[optionName].series[hoveredIndex].pieData.startRatio
            endRatio = this[optionName].series[hoveredIndex].pieData.endRatio
            k = this[optionName].series[hoveredIndex].pieStatus.k
            // 对当前点击的扇形，执行取消高亮操作（对 option 更新）
            this[optionName].series[
              hoveredIndex
            ].parametricEquation = getParametricEquation(
              startRatio,
              endRatio,
              isSelected,
              isHovered,
              k,
              this[optionName].series[hoveredIndex].pieData.value
            )
            this[optionName].series[hoveredIndex].pieStatus.hovered = isHovered
            // 将此前记录的上次选中的扇形对应的系列号 seriesIndex 清空
            hoveredIndex = ''
          }
          // 如果触发 mouseover 的扇形不是透明圆环，将其高亮（对 option 更新）
          if (
            params.seriesName !== 'mouseoutSeries' &&
            params.seriesName !== 'pie2d'
          ) {
            // 从 option.series 中读取重新渲染扇形所需的参数，将是否高亮设置为 true。
            isSelected =
              this[optionName].series[params.seriesIndex].pieStatus.selected
            isHovered = true
            startRatio =
              this[optionName].series[params.seriesIndex].pieData.startRatio
            endRatio = this[optionName].series[params.seriesIndex].pieData.endRatio
            k = this[optionName].series[params.seriesIndex].pieStatus.k
            // 对当前点击的扇形，执行高亮操作（对 option 更新）
            this[optionName].series[
              params.seriesIndex
            ].parametricEquation = getParametricEquation(
              startRatio,
              endRatio,
              isSelected,
              isHovered,
              k,
              this[optionName].series[params.seriesIndex].pieData.value + 5
            )
            this[optionName].series[
              params.seriesIndex
            ].pieStatus.hovered = isHovered
            // 记录上次高亮的扇形对应的系列号 seriesIndex
            hoveredIndex = params.seriesIndex
          }
          // 使用更新后的 option，渲染图表
          myChart.setOption(this[optionName])
        }
      })
      // 修正取消高亮失败的 bug
      myChart.on('globalout', () => {
        // 准备重新渲染扇形所需的参数
        let isSelected
        let isHovered
        let startRatio
        let endRatio
        let k
        if (hoveredIndex !== '') {
          // 从 option.series 中读取重新渲染扇形所需的参数，将是否高亮设置为 true。
          isSelected = this[optionName].series[hoveredIndex].pieStatus.selected
          isHovered = false
          k = this[optionName].series[hoveredIndex].pieStatus.k
          startRatio = this[optionName].series[hoveredIndex].pieData.startRatio
          endRatio = this[optionName].series[hoveredIndex].pieData.endRatio
          // 对当前点击的扇形，执行取消高亮操作（对 option 更新）
          this[optionName].series[
            hoveredIndex
          ].parametricEquation = getParametricEquation(
            startRatio,
            endRatio,
            isSelected,
            isHovered,
            k,
            this[optionName].series[hoveredIndex].pieData.value
          )
          this[optionName].series[hoveredIndex].pieStatus.hovered = isHovered
          // 将此前记录的上次选中的扇形对应的系列号 seriesIndex 清空
          hoveredIndex = ''
        }
        // 使用更新后的 option，渲染图表
        myChart.setOption(this[optionName])
      })
    },
    // 自适应宽高
    changeSize() {
      this.statusChart.resize()
    }
  }
}
</script>

<style lang="scss" scoped>
.modular {

  .maintain_cont {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    padding-top: 0.5rem;

    .item {
      width: 100%;
      position: relative;
      display: flex;
      justify-content: center;


      .color2 {
        color: #eed55f !important;
        background-color: #eed55f !important;
      }

      .color3 {
        color: #39e0be !important;
        background-color: #39e0be !important;
      }

      .color4 {
        color: #53bbf0 !important;
        background-color: #53bbf0 !important;
      }

      ul {
        display: flex;
        width: 73%;
        justify-content: space-between;

        li {
          font-size: 0.12rem;
          display: flex;
          align-items: center;
          color: #fff;
          padding-bottom: .1rem;

          span {
            font-size: .12rem;
            color: #fff;
            font-weight: 400;
            margin: 0 0.05rem;

            &:nth-child(3) {
              color: #EED55F;
              font-family: 'din';
              font-size: .16rem;
              font-weight: bold;
              margin: 0 .17rem 0 -0.08rem;
              background: transparent !important;
            }
          }

          &:nth-child(4) {
            span {
              letter-spacing: 0;

              &:nth-child(3) {
                margin: -0.03rem .15rem 0 .17rem;
                font-size: .2rem;
              }
            }
          }

          .circular {
            width: .1rem;
            height: .1rem;
            background: #db7046;
            border-radius: 5px;
          }
        }
      }
    }

    .loss_cont {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .loss_cont_left {
        width: 40%;
        display: flex;
        flex-direction: column;

        .loos_item {
          padding: 0.33rem 0 0 0.4rem;

          h2 {
            color: #fff;
            font-size: 0.14rem;
            width: 100%;
            height: 0.19rem;
            background: url(@/assets/img/jx.png) no-repeat;
            background-size: 65% 100%;
            position: relative;

            span {
              position: absolute;
              top: -0.05rem;
              left: 0.03rem;
            }
          }

          h3 {
            font-size: 0.13rem;
            color: #fff;
            padding: 0.03rem 0 0 0.1rem;
            display: flex;
            align-items: center;

            span {
              font-size: 0.24rem;
              font-weight: bold;
              color: #50D5FD;
              background: linear-gradient(180deg, #41D9FF 0%, #419EFE 99.5849609375%);
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
            }

            h4 {
              opacity: .5;
              font-size: 0.13rem;
              color: #fff;
              margin-top: 0.05rem;
            }
          }
        }
      }

      .loss_cont_right {
        width: 60%;

        .chart-container {
          width: 100%;
          height: 2rem;
          position: relative;

          .chart {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1;
          }

          .bg {
            position: absolute;
            bottom: 9%;
            left: 50%;
            width: 42%;
            height: 47%;
            z-index: 0;
            border-radius: 50%;
            background: no-repeat center;
            box-shadow: 0 0 5px 1px rgba(5, 148, 214, 0.7);
            // background-image: url(@/assets/img/aperture.png);
            background-size: 100% 100%;
            transform: translateX(-50%);
          }
        }
      }
    }
  }
}
</style>
